package com.yupi.oj.judge;

import cn.hutool.json.JSONUtil;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.judge.codesandbox.CodeSandBox;
import com.yupi.oj.judge.codesandbox.CodeSandBoxFactory;
import com.yupi.oj.judge.codesandbox.CodeSandBoxProxy;
import com.yupi.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.yupi.oj.judge.codesandbox.model.ExecuteCodeResponse;
import com.yupi.oj.judge.languageManage.LanguageManage;
import com.yupi.oj.judge.strategy.JudgeContext;
import com.yupi.oj.judge.strategy.JudgeStrategy;
import com.yupi.oj.model.dto.question.JudgeCase;
import com.yupi.oj.model.dto.questionSubmit.JudgeInfo;
import com.yupi.oj.model.entity.Question;
import com.yupi.oj.model.entity.QuestionSubmit;
import com.yupi.oj.model.enums.JudgeQuestionMessage;
import com.yupi.oj.model.enums.QuestionSubmitStatus;
import com.yupi.oj.model.vo.QuestionSubmitVO;
import com.yupi.oj.service.QuestionService;
import com.yupi.oj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {
    @Autowired
    private QuestionSubmitService questionSubmitService;
    @Autowired
    private QuestionService questionService;
    @Value("${codeSandBox.type:example}")
    private String type;

    @Override
    public QuestionSubmitVO doJudge(Long questionSubmitId) {
        //根据传递的题目提交id，查询出题目提交是否存在
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        Long id = questionSubmit.getId();
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        Long questionId = questionSubmit.getQuestionId();
        Integer status = questionSubmit.getStatus();
        //根据题目id，查询出题目的信息
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        //如果题目提交状态不是’待判题‘，那么不能重复提交
        if (!Objects.equals(status, QuestionSubmitStatus.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "正在判题");
        }
        //若已经在判题中那么修改题目提交状态变为判题中
        questionSubmit = new QuestionSubmit();
        questionSubmit.setId(id);
        questionSubmit.setStatus(QuestionSubmitStatus.RUNNING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmit);
        if (!update) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        String judgeCase = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream()
                .map(JudgeCase::getInput)
                .collect(Collectors.toList());

        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .inputList(inputList)
                .language(language)
                .code(code)
                .build();

//        执行代码沙箱返回执行信息
        CodeSandBox codeSandBox = CodeSandBoxFactory.getCodeSandBox(type);
        CodeSandBoxProxy codeSandBoxProxy = new CodeSandBoxProxy(codeSandBox);
        ExecuteCodeResponse executeCodeResponse = codeSandBoxProxy.codeExecute(executeCodeRequest);
        Integer executeStatus = executeCodeResponse.getStatus();
        //判断执行过程是否有异常
        if(Objects.equals(executeStatus, QuestionSubmitStatus.SUCCESS.getValue())){
            QuestionSubmitVO questionSubmitVO = new QuestionSubmitVO();
            JudgeInfo judgeInfo = new JudgeInfo();
            judgeInfo.setMessage(JudgeQuestionMessage.RUNTIME_ERROR.getValue());
            questionSubmitVO.setStatus(QuestionSubmitStatus.FAILED.getValue());
            questionSubmitVO.setJudgeInfo(judgeInfo);
            return questionSubmitVO;
        }
        if(Objects.equals(executeStatus, QuestionSubmitStatus.FAILED.getValue())){
            QuestionSubmitVO questionSubmitVO = new QuestionSubmitVO();
            JudgeInfo judgeInfo = new JudgeInfo();
            judgeInfo.setMessage(JudgeQuestionMessage. COMPILE_ERROR.getValue());
            questionSubmitVO.setStatus(QuestionSubmitStatus.FAILED.getValue());
            questionSubmitVO.setJudgeInfo(judgeInfo);
            return questionSubmitVO;
        }
        List<String> outputList = executeCodeResponse.getOutputList();

        List<String> RightOutputList = judgeCaseList.stream()
                .map(JudgeCase::getOutput)
                .collect(Collectors.toList());
        //比较输出结果
        JudgeInfo judgeInfo = executeCodeResponse.getJudgeInfo();
        JudgeStrategy languageJudge = LanguageManage.getLanguageJudge(language);
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setOutputList(outputList);
        judgeContext.setRightOutputList(RightOutputList);
        judgeContext.setQuestion(question);
        judgeContext.setJudgeInfo(judgeInfo);
        //判题结果信息
        String responseMessage = languageJudge.doJudge(judgeContext);
        //修改questionSubmit数据库
        questionSubmit = new QuestionSubmit();
        questionSubmit.setId(id);
        judgeInfo.setMessage(responseMessage);
        questionSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        if(!responseMessage.equals(JudgeQuestionMessage.ACCEPTED.getValue())){
            questionSubmit.setStatus(QuestionSubmitStatus.FAILED.getValue());
        }else {
            questionSubmit.setStatus(QuestionSubmitStatus.SUCCESS.getValue());
        }
        boolean b = questionSubmitService.updateById(questionSubmit);
        if (!b) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更改数据失败");
        }
        //返回信息
        questionSubmit = questionSubmitService.getById(id);
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        return questionSubmitVO;
    }
}
